var express = require('express');
var session = require('express-session');
var SQLiteStore = require('connect-sqlite3')(session);
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var booksRouter = require('./routes/books');
var bookshelvesRouter = require('./routes/bookshelves');
var reivewsRouter = require('./routes/reviews');

var dbInit = require('./controller/init');

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//注册中间件：创建数据库
app.use(dbInit());

// 构建Session会话，存储在Sqlite数据库中
app.use(session({
    secret: 'Sfsd23@dkljfadajlDvcadfa2ojad#ad!',
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, //一周
    store: new SQLiteStore({
        dir: './sqlite',
        db: 'mylibrary.db'
    })
}));

app.all('*', function (req, res, next) {
    let origin = null;

    const allowOrigin = ['http://localhost:8080', 'http://127.0.0.1:8080'];
    if (allowOrigin.find(value => {return value === req.headers.origin })) {
        origin = req.headers.origin;
    }
    res.header("Access-Control-Allow-Origin", origin);
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/books', booksRouter);
app.use('/bookshelves', bookshelvesRouter);
app.use('/reviews', reivewsRouter);

module.exports = app;
